package com.diaohaiwen.framework.openapi.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.diaohaiwen.common.exception.GlobalException;
import com.diaohaiwen.common.obj.Result;
import feign.Response;
import feign.Util;
import feign.codec.Decoder;

import java.io.IOException;
import java.lang.reflect.Type;

import static feign.Util.UTF_8;
/**
 * @author 刁海文
 * @since 2023/6/15 21:30
 * @Remark
 */
public class FeignResultDecoder implements Decoder {

    @Override
    public Object decode(final Response response, Type type) throws IOException, GlobalException {


        String str = Util.toString(response.body().asReader(UTF_8));
        //对结果进行转换
        JSONObject object = JSON.parseObject(str);
        Result<byte[]> result = object.toJavaObject(new TypeReference<>() {
        });
        //如果返回错误，且为内部错误，则直接抛出异常
        if (result.fail()) {
            throw new GlobalException(result.getStatus(), result.getMsg());
        }
        try {
            return JSON.parseObject(result.getData(), type);
        } catch (JSONException e) {
            return result.getData();
        }
    }

}
